﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using DeadDog;
using SC2parser.Model;
using SC2parser.Function;

namespace SC2parser.Parsing
{
    class BracketParser
    {
        public BracketParser(string liquipediaPage)
        {
            LiquipediaPage = new URL(liquipediaPage);
        }

        private URL liquipediaPage;
        public URL LiquipediaPage
        { 
            get {return liquipediaPage; }
            set {liquipediaPage = value; }
        }

        public string[] GetSourceMLG(URL page)
        {
            SCBuffer buffer = new SCBuffer("MLGBuffer.xml");
            string source = buffer.ReadURL(page.Address);
            source = source.CutToFirst("<textarea id=", CutDirection.Left, false);
            source = source.CutToFirst("</textarea>", CutDirection.Right, false);
            source = source.CutToFirst("|", CutDirection.Left, false);
            buffer.Save("MLGBuffer.xml");

            return source.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
        }

        public string[] GetSourceGSL(URL page)
        {
            SCBuffer buffer = new SCBuffer("MLGBuffer.xml");
            string source = buffer.ReadURL(page.Address);
            source = source.CutToFirst("=== Bracket ===", CutDirection.Left, false);
            source = source.CutToFirst("}}", CutDirection.Right, false);
            //source = source.CutToFirst("|", CutDirection.Left, false);
            buffer.Save("MLGBuffer.xml");

            return source.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
        }

        public List<Match> GetMatches(string[] source)
        {
            List<Match> matches = new List<Match>();
            List<Player> Players = new List<Player>();

            foreach (string line in source)
            {

                if (line.Contains("score="))
                {
                    string name = line.CutToSection("=", "|", true);
                    string race = line.CutToSection("race=", "|", true);
                    string score = line.CutToSection("score=", "|", true);
                    string flag = line.CutToFirst("flag=", CutDirection.Left, true);
                    
                    Players.Add(new Player(name, race.stringToRace(), score.stringToWins(), flag));

                }
            }

            for (int i = 0; i < Players.Count; i = i + 2)
            {
                matches.Add(new Match(Players.ElementAt(i), Players.ElementAt(i + 1), (i + 1) / 2));
            }

            return matches;
        }

        public List<Match> ParseBracket(string url)
        {
            return GetMatches(GetSourceMLG(new URL(url)));
        }
    }
}
